#coding=utf-8
import sys,os,json,time
sys.path.append(os.path.join(os.getcwd())) #将程序执行路径添加到系统默认包路径

from flask import Flask
from flask import request
from flask import render_template
from besteee import common
import view,configs,models
from exts import db

#获取当前脚本的绝对路径(不包括脚本文件名)
absPyPath=os.path.dirname(os.path.abspath(__file__))
templatePath=os.path.join(absPyPath,'template') #修改模板路径
app = Flask(
    __name__,
    template_folder=templatePath,
    static_folder='static', 
)
# 加载配置文件
app.config.from_object(configs)
# db绑定app
db.init_app(app)

#批量注册通用页面路由表 view.nav
app=view.forAdd(app)

#添加默认首页路由表
app.add_url_rule('/',view_func=view.normalView,defaults={'key':'fax','key2':'fax'})

@app.route('/faxUpload.html',methods=['POST'])
def faxUload():
    dayTime=common.get_normalDay()
    path=os.path.join(absPyPath,'static','upload',dayTime)
    common.makeDirs(path)

    file=request.files['file']
    file_name=file.filename

    path=os.path.join(path,file_name)
    file.save(path)
    result={
        "code": 0
        ,"msg":path 
        ,"data": {
            "src": "http://cdn.layui.com/123.jpg"
        }
    }      
    return json.dumps(result,ensure_ascii=False)

@app.route('/get_config.html',methods=['POST'])
def get_config():
    if request.method == 'POST':
        config=models.Fax_config().query.filter_by(id=1).first()
        #config=models.Fax_config()
        result=request.get_json()

        if result['type']=='load':
            data=models.class_to_dict( config)
            data['msg']='数据载入成功！'
        elif result['type']=='update':
            print(result)
            config.account=result['formData']['account']
            config.sender1=result['formData']['sender1']
            config.sender2=result['formData']['sender2']
            db.session.commit()
            data={'msg':'修改成功！'}

    return json.dumps(data,ensure_ascii=False)

@app.route('/faxSend.html',methods=['POST'])
def faxSend():
    if request.method == 'POST':
        result=request.get_json()
        send=models.aofax_send_task()
        send.title=result['formData']["title"]
        send.ic=86
        send.ldc=result['formData']["ldc"]
        send.fax=result['formData']["fax"]
        send.account=result['formData']["account"]
        send.sender1=result['formData']["sender1"]
        send.sender2=result['formData']["sender2"]
        send.receiver1=result['formData']["receiver1"]
        send.receiver2=result['formData']["receiver2"]
        #send.sendfile=result["sendfile"]
        send.sendfile="d:\\11.txt"
        send.sendflag=result['formData']["sendflag"]
        send.line=result['formData']["line"]
        send.status=0
        send.extinfo='test'
        send.retcode=0
        send.sendtime=time.time()
        send.faxfile=''
        send.reserve1=0
        send.reserve2=0
        send.ext1=0
        send.ext2=0
        send.memo=''
        # 将新创建的用户添加到数据库会话中
        db.session.add(send)
        # 将数据库会话中的变动提交到数据库中, 记住, 如果不 commit, 数据库中是没有变化的.
        print(db.session.commit() )   
        return json.dumps([send.title,send.ldc],ensure_ascii=False)
    else:
        return '<h1>只接受post请求！</h1>'


@app.route('/layui.html')
def layui():
    name='layui'
    return  render_template('layui.html',  name=name)

@app.route('/hello')
@app.route('/hello/<name>')
def  hello(name=None):
    try:
        path=common.base64de(name)
        folder_path, file_name = os.path.split(path)
        return f'''
            文件所在文件夹： {folder_path}<br>
            文件名：{file_name}
        '''
    except:
        return '你所提交的base64编码字符串有误！' 
    #return  render_template('hello.html',  name=name)

@app.route('/voc')
@app.route('/voc/path')
def vocToWord():
    return render_template(
        # 渲染模板语言
        'base.html',app=app,title="test"
    )